/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.kem.android.positioner;

import java.util.Set;

import net.kem.android.positioner.tools.IntEditTextPreference;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

public class PreferencesFromXml extends PreferenceActivity {
	private SharedPreferences prefs;
	private OnSharedPreferenceChangeListener paramOnSharedPreferenceChangeListener;
	private EditTextPreference hostPort, userName, password, wifiId, wifiHostPort;

	// Our handler for received Intents. This will be called whenever an Intent with an action named "toastEvent" is broadcasted.
	private BroadcastReceiver toastMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// Get extra data included in the Intent
			String to = intent.getStringExtra("to");
				if (to != null && (to.length()==0 || PreferencesFromXml.class.getName().equals(to))) {
				String message = intent.getStringExtra("message");
				if (message != null) {
					Utils.toast(getApplicationContext(), message, Toast.LENGTH_SHORT);
				}
			}
		}
	};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
        // Get the xml/preferences.xml preferences
     	prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

     	paramOnSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener()  {
     		@Override
			public void onSharedPreferenceChanged(SharedPreferences paramSharedPreferences, String paramString) {
     			System.out.println(paramSharedPreferences);
     			System.out.println(paramString);			//prfUsername	ToggleGPSAutoSettings
				// TODO Auto-generated method stub
			}
		};
     	prefs.registerOnSharedPreferenceChangeListener(paramOnSharedPreferenceChangeListener);

     	final OnPreferenceChangeListener preferenceSummaryTracker = new PreferenceSummaryTracker();

     	hostPort = (EditTextPreference)findPreference(Settings.PARAM_HOST_PORT);
     	hostPort.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	userName = (EditTextPreference)findPreference(Settings.PARAM_USERNAME);
     	userName.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	password = (EditTextPreference)findPreference(Settings.PARAM_PASSWORD);
     	password.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	wifiId = (EditTextPreference)findPreference(Settings.PARAM_HOME_WIFI_ID);
     	wifiId.setOnPreferenceChangeListener(preferenceSummaryTracker);
     	wifiHostPort = (EditTextPreference)findPreference(Settings.PARAM_WIFI_HOST_PORT);
     	wifiHostPort.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	final IntEditTextPreference gpsDistance = (IntEditTextPreference)findPreference(Settings.PARAM_GPS_REFRESH_DISTANCE);
     	gpsDistance.setSummary(String.valueOf(Settings.getGPSRefreshDistance()));
     	gpsDistance.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	final IntEditTextPreference gpsRefreshInterval = (IntEditTextPreference)findPreference(Settings.PARAM_GPS_REFRESH_INTERVAL);
     	gpsRefreshInterval.setSummary(String.valueOf(Settings.getGPSRefreshInterval()));
     	gpsRefreshInterval.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	final IntEditTextPreference poiRadius = (IntEditTextPreference)findPreference(Settings.PARAM_POI_RADIUS);
     	poiRadius.setSummary(String.valueOf(Settings.getPOIRadius()));
     	poiRadius.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	final IntEditTextPreference gpsAccuracyThreshold = (IntEditTextPreference)findPreference(Settings.PARAM_GPS_ACCURACY_THRESHOLD);
     	gpsAccuracyThreshold.setSummary(String.valueOf(Settings.getGPSAccuracyThreshold()));
     	gpsAccuracyThreshold.setOnPreferenceChangeListener(preferenceSummaryTracker);

     	final PreferenceScreen preferenceScreen = (PreferenceScreen)findPreference(Settings.PARAM_GPSSETTINGS);
     	CheckBoxPreference checkBoxAutoGPS = (CheckBoxPreference)findPreference(Settings.PARAM_IS_AUTO_GPS_SETTINGS);
     	checkBoxAutoGPS.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				gpsDistance.setEnabled(!(Boolean)newValue);
				gpsRefreshInterval.setEnabled(!(Boolean)newValue);
		     	poiRadius.setEnabled(!(Boolean)newValue);
		     	gpsAccuracyThreshold.setEnabled(!(Boolean)newValue);
		     	preferenceScreen.setSummary((Boolean)newValue? ((CheckBoxPreference)preference).getSummaryOn(): ((CheckBoxPreference)preference).getSummaryOff());
				return true;
			}
		});

     	CheckBoxPreference checkBoxKeepServiceRunning = (CheckBoxPreference)findPreference(Settings.PARAM_KEEP_SERVICE_RUNNING);
     	checkBoxKeepServiceRunning.setChecked(prefs.getBoolean(Settings.PARAM_KEEP_SERVICE_RUNNING, true));
     	checkBoxKeepServiceRunning.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
     		@Override
     		public boolean onPreferenceChange(Preference preference, Object newValue) {
     			if((Boolean)newValue) {
     				startPositionerService();
     			} else {
     				stopPositionerService();
     			}
     			gpsDistance.setEnabled(!(Boolean)newValue);
     			gpsRefreshInterval.setEnabled(!(Boolean)newValue);
     			poiRadius.setEnabled(!(Boolean)newValue);
     			gpsAccuracyThreshold.setEnabled(!(Boolean)newValue);
     			preferenceScreen.setSummary((Boolean)newValue? ((CheckBoxPreference)preference).getSummaryOn(): ((CheckBoxPreference)preference).getSummaryOff());
     			return true;
     		}
     	});

     	gpsDistance.setEnabled(!checkBoxAutoGPS.isChecked());
		gpsRefreshInterval.setEnabled(!checkBoxAutoGPS.isChecked());
     	poiRadius.setEnabled(!checkBoxAutoGPS.isChecked());
     	gpsAccuracyThreshold.setEnabled(!checkBoxAutoGPS.isChecked());
     	preferenceScreen.setSummary(checkBoxAutoGPS.isChecked()? checkBoxAutoGPS.getSummaryOn(): checkBoxAutoGPS.getSummaryOff());

        // Get reference to POI list.
        ListPreference listPref = (ListPreference)findPreference(Settings.PARAM_POIS);
        // Populate the POI list.
        int i = 0;
        Set<POI> pois = Settings.getPOIs();
        CharSequence[] entries = new String[pois.size()];
        CharSequence[] entryValues = new String[pois.size()];
        for(POI poi: pois) {
        	entries[i] = poi.getName();
        	entryValues[i] = String.valueOf(poi.getId());
        	i++;
        }
        listPref.setEntries(entries);
        listPref.setEntryValues(entryValues);
        listPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				int poiId = Integer.parseInt(newValue.toString());
				POI poi = Settings.getPOIById(poiId);
				Intent intent = new Intent(PreferencesFromXml.this, POIActivity.class).putExtra(POIActivity.EXTRA_MESSAGE_POI, poi);
				startActivity(intent);
				return false;
			}
		});

        // Register to receive messages from PositionerService.
        LocalBroadcastManager.getInstance(this).registerReceiver(toastMessageReceiver, new IntentFilter("toastEvent"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        prefs.unregisterOnSharedPreferenceChangeListener(paramOnSharedPreferenceChangeListener);
        // Unregister since the activity is about to be closed.
		if(toastMessageReceiver != null) {
			LocalBroadcastManager.getInstance(this).unregisterReceiver(toastMessageReceiver);
		}
    }

    private ComponentName startPositionerService() {
		Intent intent = new Intent(this, PositionerService.class);
		ComponentName res = startService(intent);
		return res;
	}
	private boolean stopPositionerService() {
		Intent intent = new Intent(this, PositionerService.class);
		boolean res = stopService(intent);
		return res;
	}

//    private void getPrefs() {
//    	EditTextPreference hostPort = (EditTextPreference)findPreference("prfServerHostPort");
//    	hostPort.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
//    	listPreference = prefs.getString("prfServerHostPort", "znetwork.no-ip.org:80");
//    	hostPort.setDefaultValue(text);
//    	hostPort.setText(text);
//
//		// Get the xml/preferences.xml preferences
//		checkboxPreference = prefs.getBoolean("checkboxPref", true);
//		editTextPreference = prefs.getString("editTextPref", "Nothing has been entered");
//		ringtonePreference = prefs.getString("ringtonePref", "DEFAULT_RINGTONE_URI");
//		secondEditTextPreference = prefs.getString("SecondEditTextPref", "Nothing has been entered");
//		// Get the custom preference
//		SharedPreferences mySharedPreferences = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
//		customPref = mySharedPreferences.getString("myCusomPref", "");
//	}

    class PreferenceSummaryTracker implements OnPreferenceChangeListener {
		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			preference.setSummary(newValue.toString());
			if(preference == hostPort) {
				Settings.setHostPort(newValue.toString());
				return true;
			}
			if(preference == userName) {
				Settings.setUsername(newValue.toString());
				return true;
			}
			if(preference == password) {
				Settings.setPassword(newValue.toString());
				return true;
			}
			if(preference == wifiId) {
				Settings.setHomeWiFiId(newValue.toString());
				return true;
			}
			if(preference == wifiHostPort) {
				Settings.setWiFiHostPort(newValue.toString());
				return true;
			}
			if(preference instanceof IntEditTextPreference) {
				//prefs.edit().putInt(preference.getKey(), Integer.parseInt(newValue.toString())).commit();
				Settings.setValue(preference.getKey(), Integer.parseInt(newValue.toString()));
				return false;	// Do not update the state of the Preference with the new value automatically.
			}
			return true;
		}

    }
}